package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String uploadDirPath;
    @PostMapping("/upload")
  public R<String> upload(MultipartFile file) throws IOException {
  log.info(file.getName());
  //获取上传文件本身的文件名
        String originalFilename = file.getOriginalFilename();
        //获得扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //为了避免多个上传操作的文件重名，重新为图片随机命名
       String uploadNewRandomFileName= UUID.randomUUID().toString()+suffix;
       //将上传的文件保存到服务器端

        File uploadFile=new File(uploadDirPath,uploadNewRandomFileName);
        //读取上传的文件内容，写出到指定的文件位置
      file.transferTo(uploadFile);
      //返回文件名，为后续下载准备

        return R.success(uploadNewRandomFileName);
  }
        @GetMapping("/download")
      public void download(String name, HttpServletResponse response) throws IOException {
        //将文件读取到程序中
          File sourceFile = new File(uploadDirPath + name);
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            //获取向浏览器响应的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //响应图片
            //定义变量，用于临时存储每个字节
            int b;
            while ((b=fileInputStream.read())!=-1){
                outputStream.write(b);
            }
            //关闭io流
            fileInputStream.close();
            outputStream.close();
            //设置响应头
            response.setContentType("/image/jpeg");





      }
}
